package com.example.hospitaltraining.controller;

import cn.hutool.core.io.FileUtil;
import com.example.hospitaltraining.common.R;
import com.example.hospitaltraining.config.AuthAccess;
import com.example.hospitaltraining.mapper.FileMapper;
import com.example.hospitaltraining.pojo.Files;
import com.example.hospitaltraining.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件上传相关接口
 */
@RestController
@RequestMapping("/files")
public class FileControer {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Autowired
    private FileService fileService;

    /**
     * 文件上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @AuthAccess
    @PostMapping("/upload")
    public R upload(@RequestParam MultipartFile file) throws IOException {
        String url = fileService.upload(file);
        StringSelection stringSelection = new StringSelection("ss1");

        return R.ok().put("data",url);
    }

    /**
     * 文件下载接口 http://localhost:8089/file/{uuid}  http://andysama.work:8089/files/7697f930284c46d594418c92e3b2514a.png
     * @param fileUUID
     * @param response
     * @throws IOException
     */
    @GetMapping("/{fileUUID}")
    private void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        //根据文件唯一标识码获取文件
        File newFile = new File(fileUploadPath + fileUUID);
        //设置输出流的格式
        ServletOutputStream os = response.getOutputStream();

        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(newFile));
        os.flush();
        os.close();

    }

    @AuthAccess
    @GetMapping("/getbyid/{id}")
    public void upload(@PathVariable Long id, HttpServletResponse response) throws IOException {
        if(id==1||id==2||id==3){
            Files byId = fileService.getById(id);
            String[] split = byId.getUrl().split("/");
            System.out.println(split[split.length-1]);
            //根据文件唯一标识码获取文件
            File newFile = new File(fileUploadPath + split[split.length-1]);
            //设置输出流的格式
            ServletOutputStream os = response.getOutputStream();

            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode( split[split.length-1], "UTF-8"));
            response.setContentType("application/octet-stream");
            // 读取文件的字节流
            os.write(FileUtil.readBytes(newFile));
            os.flush();
            os.close();
        }
    }





    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id){
//        boolean delete = fileService.removeById(id);
        Files byId = fileService.getById(id);
        byId.setIsDelete(1); //0代表在1代表已删除
        boolean delete = fileService.updateById(byId);
        if(delete){
            return R.ok("删除成功");
        }else {
            return R.error("删除失败");
        }
    }

    @DeleteMapping("/del/batch")
    public R deleteBatch(@RequestBody List<Long> ids){
//        boolean delete = fileService.removeByIds(ids);

        List<Files> filesList = fileService.listByIds(ids);
        for (Files files : filesList) {
            //0代表在1代表已删除
            files.setIsDelete(1);
        }
        boolean delete = fileService.updateBatchById(filesList);

        if(delete){
            return R.ok("批量删除成功");
        }else {
            return R.error("批量删除失败");
        }
    }
}
